<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-dialog title="分配权限" :visible="showDialog" style="height:600px;" @close="closeFn">

        <!-- show-checkbox显示复选框，node-key唯一标识 default-expand-all默认展开所有项 父子不关联 -->
        <el-tree
          ref="tree"
          :data="permissionList"
          :props="{label:'title'}"
          show-checkbox
          node-key="id"
          default-expand-all
          :check-strictly="true"
          :default-checked-keys="permDetail"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeFn">取 消</el-button>
          <el-button type="primary" @click="confirmFn">确定</el-button>
        </div>
      </el-dialog>
    </div></div>
</template>
<script>
import { getpermission } from '@/api/permission'
import { getRoleDetailById, editRole } from '@/api/role'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permissionList: [],
      permDetail: [],
      roleId: '',
      permIds: []
    }
  },
  created() {
    /* 获取所有的权限列表 */
    this.getPermList()
  },
  methods: {
    /* 确认按钮 */
    async confirmFn() {
      this.permIds = this.$refs.tree.getCheckedKeys()
      console.log(this.permIds)
      /* 只用传permIds就行 */
      await editRole({ id: this.roleId, permissions: this.permIds })
      this.closeFn()
    },
    /* 获取点击角色详情拿角色的权限列表里面的id */
    async getRoleDetailById(id) {
      // console.log(id)
      /* 存角色id */
      this.roleId = String(id)
      const res = await getRoleDetailById(id)
      // console.log(this.roleId)
      // console.log(res)
      this.permDetail = res.permissions
      // console.log(this.permDetail)
      this.permIds = this.permDetail.map(item => item.id)
      // console.log('this.permIds', this.permIds)
      /* 获取tree的方法 把id传进去 */
      this.$refs.tree.setCheckedKeys(this.permIds)
    },
    /* 获取所有的权限列表 */
    async getPermList() {
      const res = await getpermission({
        _limit: 100,
        _start: 0
      })
      this.permissionList = this.listToTree(res, 0)
    },
    /* 列表转数形结构 */
    listToTree(arr, id) {
      const list = []
      arr.forEach(item => {
        if (Number(item.pid) === id) {
          list.push(item)
          item.children = []
          arr.forEach(value => {
            if (Number(value.pid) === item.id) {
              item.children.push(value)
            }
          })
        }
      })
      // console.log('list', list)
      return list
    },
    /* 关闭弹框 */
    closeFn() {
      /* 关闭弹框 */
      this.$emit('update:showDialog', false)
      /* 数组中数据设为空数组 */
      this.$refs.tree.setCheckedKeys([])
      this.$parent.getRoleLists()
    }
  }
}
</script>

<style>

</style>
